/*
Copyright (c) 2010 Tomas Lindquist Olsen

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <cstring>

#include <string>

extern "C" {
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
}

#include "gui.h"

extern int tolua_binding_open(lua_State*);

static bool read_config(lua_State* L, int argc, const char** argv);
static int doscript_func(lua_State* L);

static bool call_lua_func(lua_State*L, int nargs, int nres, int nerr = 0);
static bool call_lua_file(lua_State* L, const char* path);

#ifndef INSTALL_PREFIX
#define INSTALL_PREFIX "/usr"
#endif

struct LuaState
{
    lua_State* L;
    LuaState()
    :   L(0)
    {
        L = luaL_newstate();
    }
    ~LuaState()
    {
        if (L)
            lua_close(L);
    }

    operator lua_State*() { return L; }
};

int main(int argc, const char** argv)
{
    LuaState L;

    luaL_openlibs(L);
	tolua_binding_open(L);
    lua_register(L, "doscript", doscript_func);

    std::string user_dir;
    user_dir += getenv("HOME");
    user_dir += "/.lua-applets";

    lua_pushstring(L, user_dir.c_str());
    lua_setglobal(L, "userconfigdir");

    // first we run the lua-applet library
    std::string lib_path = user_dir + "/lua-applets.lua";
    if (!call_lua_file(L, lib_path.c_str()))
    {
        fprintf(stderr, "failed to load the lua-applets library\n");
        return EXIT_FAILURE;
    }

    // start by calling the init func
    lua_getglobal(L,"init_lua_applets");
    if (!lua_isfunction(L, -1) || !call_lua_func(L,0,0))
    {
        fprintf(stderr, "failed to run init function\n");
        return EXIT_FAILURE;
    }

    if (!read_config(L, argc, argv))
    {
        fprintf(stderr, "failed to load configuration\n");
        return EXIT_FAILURE;
    }

    int exitcode = gui_wait_for_all(argc, argv);

    // finish off by calling the init func
    lua_getglobal(L,"exit_lua_applets");
    if (!lua_isfunction(L, -1) || !call_lua_func(L,0,0))
    {
        fprintf(stderr, "failed to run exit function\n");
        return EXIT_FAILURE;
    }

    return exitcode;
}

static bool read_config(lua_State* L, int argc, const char** argv)
{
    // check the user's HOME dir for a user-specific configuration

    lua_getfield(L, LUA_GLOBALSINDEX, "userconfigdir");
    const char* userdir = lua_tostring(L, -1);

    std::string local_path = userdir;
    local_path += "/config.lua";

    printf("local config path: %s\n", local_path.c_str());

    return call_lua_file(L, local_path.c_str());
}

static int doscript_func(lua_State* L)
{
    const char* script = luaL_checkstring(L, 1);

    lua_getfield(L, LUA_GLOBALSINDEX, "userconfigdir");

    const char* userdir = lua_tostring(L, -1);

    printf("doing script %s/%s\n", userdir, script);

    std::string path = userdir;
    path += "/";
    path += script;

    int r = call_lua_file(L, path.c_str());
    lua_pushboolean(L, r == 0 ? 1 : 0);

    return 1;
}

// TODO it would be nice to get a decent error handler function going

static bool call_lua_func(lua_State*L, int nargs, int nres, int err)
{
    int cr = lua_pcall(L,nargs,nres,0);
    if (cr != 0)
    {
        fprintf(stderr, "error occured in call to Lua:");
        fprintf(stderr, "%s\n", lua_tostring(L, -1));
        return false;
    }
    return true;
}

static bool call_lua_file(lua_State* L, const char* path)
{
    int r = luaL_loadfile(L, path);
    if (r == 0)
        return call_lua_func(L,0,0);
    fprintf(stderr, "error while loading script:\n%s\n", lua_tostring(L, -1));
    return false;
}
